package com.fyy.netty.chapter01.c1;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author fyy
 * @Description ByteBuffer的方法
 * @Date 2021/4/20 15:03
 */
public class ByteBufferMethods {

    public static void main(String[] args) {
        //创建一个ByteBuffer
        ByteBuffer buffer =
                ByteBuffer.allocate(1024); //使用java的堆内存
                ByteBuffer.allocateDirect(1024); //使用直接内存
        //写入数据
        buffer.put((byte) 0x61); //存入单独的字节
        buffer.put(new byte[]{0x62,0x63,0x64}); //存入字节数组
        //读取数据
        buffer.flip(); //切换到读模式
        System.out.println(buffer.get());
        buffer.rewind(); //重新读取数据

        buffer.mark();  //标记当前position
        buffer.reset(); //复位到上次标记的position

        System.out.println(buffer.get(2));
        //切换到写模式的两种方法
        buffer.clear(); //清空buffer,重新开始填入
        buffer.compact(); //将未读取的数据向前压缩，在其后填入

        //字符串转ByteBuffer

        ByteBuffer buffer1 = StandardCharsets.UTF_8.encode("你好");
        ByteBuffer buffer2 = Charset.forName("UTF-8").encode("你好");
        ByteBuffer buffer3 = ByteBuffer.allocate(1024);
        buffer3.put("你好".getBytes());
        ByteBuffer buffer4 = ByteBuffer.wrap("你好".getBytes());
        //ByteBuffer转字符串
        CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer1);
        System.out.println(charBuffer.toString());

    }

}
